package org.example.video.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.commons.entity.Comment;
import org.example.video.mapper.CommentMapper;
import org.example.video.service.CommentService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: authority-v3.0.7
 * @ClassName:CommentServiceImpl
 * @description: 评论列表 service实现类
 * @author:dyy
 * @Version 3.0
 **/

@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
    @Override
    public boolean removeCommentAndChildren(Long id) {
        List<Long> idsToDelete = findAllChildIds(id);
        return this.removeByIds(idsToDelete);
    }

    @Override
    public List<Long> findAllChildIds(Long parentId) {
        List<Long> childIds = new ArrayList<>();
        childIds.add(parentId); // 包含自身
        findChildrenIds(parentId, childIds);
        return childIds;
    }

    private void findChildrenIds(Long parentId, List<Long> childIds) {
        List<Comment> children = this.list(new LambdaQueryWrapper<Comment>()
                .eq(Comment::getParentId, parentId));
        for (Comment child : children) {
            childIds.add(child.getId());
            findChildrenIds(child.getId(), childIds); // 递归处理子评论
        }
    }
}
